import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/types.d';
import { ExclamationOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import { useModel } from 'umi';
import { queryHistoryRevenue, updateHistory } from '../service';
import type { RevenueTableItem } from '../types.d';

const RevenueHistoryList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const isAdmin = currUser?.role == Role.ADMIN;

  const columns: ProColumns<RevenueTableItem>[] = [
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      align: 'center',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
      width: 150,
      renderText: (_, record) => record?.ownerInfo?.ownerName || record?.ownerId,
    },
    {
      title: '统计日期',
      dataIndex: 'recordDay',
      hideInForm: true,
      valueType: 'date',
      align: 'center',
    },
    {
      title: '收费订单',
      dataIndex: 'chargedOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip: '统计时段内车辆驶出结算后，产生费用的订单数量（依据车辆驶出时间计算）',
    },
    {
      title: '录单率',
      dataIndex: 'chargePlatedOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip:
        '统计时段内车辆驶出结算后，产生费用的订单中，车牌已录入订单的占比（依据车辆驶出时间计算）',
      renderText: (_, record) => {
        if (record.chargedOrder == 0) return '0.00%';
        if (record.chargePlatedOrder == undefined) return '-';
        return ((record.chargePlatedOrder / record.chargedOrder) * 100).toFixed(2) + '%';
      },
    },
    {
      title: '免费订单',
      dataIndex: 'freeOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip: '统计时段内车辆驶出结算后，免费的订单数量（依据车辆驶出时间计算）',
    },
    {
      title: '异常订单',
      dataIndex: 'exceptOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip:
        '统计时段内车辆驶出结算后，未打印小票/未录入车牌/未缴清费用的订单（依据车辆驶出时间计算）',
    },
    {
      title: '追缴订单',
      dataIndex: 'recoveryOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip: '统计时段内追缴的订单数量（依据追缴时间计算）',
    },
    {
      title: '作废订单',
      dataIndex: 'cancelOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip: '统计时段内作废的订单数量（依据作废时间计算）',
    },
    {
      title: '会员订单',
      dataIndex: 'memberOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip: '统计时段内车辆驶出结算后，会员车辆的订单数量（依据车辆驶出时间计算）',
    },
    {
      title: '总订单',
      dataIndex: 'totalOrder',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      tooltip: '统计时段产生的订单数量（依据车辆驶入时间计算）',
    },
    {
      title: '应收金额(总)',
      dataIndex: 'payableAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      hideInTable: true,
      renderText: (_, record) => record.payableAmount / 100,
      valueType: 'money',
      tooltip: '统计时段内车辆驶出结算后，产生的总应收金额（依据车辆驶出时间计算）',
    },
    {
      title: '实收金额',
      dataIndex: 'paymentAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      hideInTable: true,
      renderText: (_, record) => record.paymentAmount / 100,
      valueType: 'money',
      tooltip: '统计时段内有效停车支付记录的总金额数(包含实时订单和欠费订单)',
    },
    {
      title: '应收金额(已录车牌)', //plateAmount
      dataIndex: 'plateAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => (record.plateAmount || 0) / 100,
      valueType: 'money',
      tooltip:
        '统计时段内车辆驶出结算后，所有已录车牌的订单产生的应收金额（仅包含统计时间内驶出的订单）',
    },
    {
      title: '实收金额(已录车牌)',
      dataIndex: 'plateActualAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => (record.plateActualAmount || 0) / 100,
      valueType: 'money',
      tooltip:
        '统计时段内车辆驶出结算后，所有已录车牌的订单的实收金额（仅包含统计时间内驶出的订单）',
    },
    {
      title: '追缴金额',
      dataIndex: 'recoveryAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => record.recoveryAmount / 100,
      valueType: 'money',
      tooltip: '统计时段内追缴的总金额（依据追缴时间计算）',
    },
    {
      title: '欠费金额(已录车牌)',
      dataIndex: 'plateArrearAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => (record.plateArrearAmount || 0) / 100,
      valueType: 'money',
      tooltip:
        '统计时段内车辆驶出结算后，所有已录车牌的订单未缴清的总金额（仅包含统计时间内驶出的订单）',
    },
    {
      title: '欠费金额',
      dataIndex: 'arrearAmount',
      align: 'center',
      hideInForm: true,
      hideInTable: true,
      hideInSearch: true,
      renderText: (_, record) => record.arrearAmount / 100,
      valueType: 'money',
      tooltip: '统计时段内车辆驶出结算后，未缴清的总金额（依据车辆驶出时间计算）',
    },
    {
      title: '会员免单金额',
      dataIndex: 'memberAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => (record.memberAmount || 0) / 100,
      valueType: 'money',
      tooltip: '统计时段内车辆驶出结算后，会员车辆免单的费用（依据车辆驶出时间计算）',
    },
    {
      title: '作废金额',
      dataIndex: 'cancelAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => (record.cancelAmount || 0) / 100,
      valueType: 'money',
      tooltip: '统计时段内作废订单的应收金额(依据作废时间计算)',
    },
    {
      title: '退款金额',
      dataIndex: 'refundedAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => (record.refundedAmount || 0) / 100,
      valueType: 'money',
      tooltip: '统计时间段内退款的金额(依据退款时间计算)',
    },
    {
      title: '会员办理数量',
      tooltip: '仅统计用户购买部分',
      dataIndex: 'memberCardCount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '会员办理金额',
      tooltip: '仅统计用户购买部分',
      dataIndex: 'memberCardAmount',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => (record.memberCardAmount || 0) / 100,
      valueType: 'money',
    },
    {
      title: '缴费率',
      dataIndex: 'plateActualAmount',
      key: 'actualAmountRate',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => {
        if (!record.plateAmount) return '-';
        return (((record.plateActualAmount || 0) / record.plateAmount) * 100).toFixed(2) + '%';
      },
      tooltip: '(实收金额 / 应收金额(已录车牌)) * 100',
    },
    {
      title: '欠费率',
      dataIndex: 'plateArrearAmount',
      key: 'arrearAmountRate',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => {
        if (!record.plateAmount) return '-';
        return (((record.plateArrearAmount || 0) / record.plateAmount) * 100).toFixed(2) + '%';
      },
      tooltip: '(欠费金额(已录车牌) / 应收金额(已录车牌)) * 100',
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      hideInTable: !isAdmin,
      render: (_, record, x, action) =>
        isAdmin
          ? [
              <a
                key={`${record._id}_up`}
                onClick={() => {
                  Modal.confirm({
                    title: '校正确认',
                    icon: <ExclamationOutlined />,
                    content:
                      '是否确认要校正当前所选项？此操作将同步校正当天当前用户名下所有路段营收统计',
                    onOk: async () => {
                      message.loading({
                        content: '正在校正...',
                        key: 'up_revenue',
                      });
                      const res = await updateHistory(record._id);
                      if (!res.success) {
                        message.error({ content: '校正失败，请稍后重试', key: 'up_revenue' });
                        return false;
                      }
                      message.success({ content: '校正成功', key: 'up_revenue' });
                      action?.reload();
                      return true;
                    },
                  });
                }}
              >
                校正
              </a>,
            ]
          : [<PlaceHolderCpn key={`${record._id}_noauth`} />],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '历史营收统计',
      }}
    >
      <ProTable<RevenueTableItem>
        rowKey="_id"
        columns={columns}
        search={{ labelWidth: 'auto' }}
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        columnEmptyText="暂无数据"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (params, sort) => {
          return await queryHistoryRevenue(params, sort);
        }}
      />
    </PageHeaderWrapper>
  );
};

export default RevenueHistoryList;
